package com.yizisu.playerlibrary.activity

import android.content.Intent
import android.content.pm.ActivityInfo
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.google.android.exoplayer2.MediaItem
import com.yizisu.playerlibrary.IYzsPlayer
import com.yizisu.playerlibrary.R
import com.yizisu.playerlibrary.helper.SimplePlayerListener
import com.yizisu.playerlibrary.view.video_view.view.PlayerRootView
import com.yizisu.playerlibrary.view.video_view.view.fullScreen
import java.io.Serializable

class FullScreenVideoActivity : AppCompatActivity(), SimplePlayerListener<IYzsPlayer.Model> {
    companion object {
        private var playerListener: SimplePlayerListener<IYzsPlayer.Model>? = null

        fun start(
            appCompatActivity: AppCompatActivity?,
            info: VideoInfo,
            listener: SimplePlayerListener<IYzsPlayer.Model>? = null,
            callIntent: Function1<Intent, Unit>? = null
        ) {
            appCompatActivity ?: return
            val oldScreen = appCompatActivity.requestedOrientation
            val intent = Intent(appCompatActivity, FullScreenVideoActivity::class.java)
            intent.putExtra("orientation", oldScreen)
            intent.putExtra("info", info)
            callIntent?.invoke(intent)
            playerListener = listener
            ActivityCompat.startActivity(appCompatActivity, intent, null)
        }

        fun start(appCompatActivity: AppCompatActivity?, url: String) {
            start(appCompatActivity, VideoInfo(0, 0, null, url))
        }


        fun start(
            appCompatActivity: AppCompatActivity?,
            url: String,
            title: String?,
            currentDuration: Long,
            listener: SimplePlayerListener<IYzsPlayer.Model>?
        ) {
            playerListener = listener
            start(appCompatActivity, VideoInfo(0, 0, title, url, currentDuration))
        }
    }

    data class VideoInfo(
        val width: Int,
        val height: Int,
        val title: String?,
        val url: String?,
        val currentDuration: Long = 0,
    ) : Serializable

    private val orientation by lazy {
        intent.getIntExtra(
            "orientation",
            ActivityInfo.SCREEN_ORIENTATION_SENSOR
        )
    }
    private val info by lazy { intent.getSerializableExtra("info") as? VideoInfo }
    private val player by lazy {
        IYzsPlayer<IYzsPlayer.Model>(this, true)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        window.fullScreen(true)
        var videoData: VideoInfo? = null
        when (intent?.action) {
            Intent.ACTION_VIEW -> {
                val data = intent?.dataString
                if (data.isNullOrBlank()) {
                    finishAfterTransition()
                    Toast.makeText(this, "没有可播放视频", Toast.LENGTH_LONG).show()
                    return
                } else {
                    videoData = VideoInfo(
                        0,
                        0,
                        intent.getStringExtra(Intent.EXTRA_TITLE)
                            ?: intent.extras?.getString(Intent.EXTRA_TITLE),
                        data
                    )
                }
            }
            else -> {
                videoData = info
            }
        }
        if (videoData?.url == null) {
            finishAfterTransition()
            Toast.makeText(this, "播放地址未null", Toast.LENGTH_LONG).show()
            return
        }
        setOrientation(videoData)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_full_screen_video)
        player.addPlayerListener(this)
        player.setAudioForceEnable(true)
        playerListener?.let {
            player.addPlayerListener(it)
        }
        playerListener = null
        val playerView = findViewById<PlayerRootView>(R.id.playerView)
        playerView.setPlayerAndInitHelper(player)
        playerView.post {//保证view意见被添加到window
            player.prepare(mutableListOf(object : IYzsPlayer.Model() {
                override fun onMediaItem(uriCall: (MediaItem?, Throwable?, Boolean) -> Unit) {
                    uriCall.invoke(MediaItem.fromUri(videoData.url!!), null, false)
                }

                override fun getTitle(): CharSequence? {
                    return videoData.title
                }
            }), positionMs = videoData.currentDuration)
        }
    }

    /**
     * 根据宽高设置视频方向
     */
    private fun setOrientation(info: VideoInfo?) {
        info ?: return
        val width = info.width
        val height = info.height
        try {
            requestedOrientation = if (width <= 0 || height <= 0) {
                orientation
            } else {
                if (width > height) {
                    ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
                } else {
                    ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
                }
            }
        } catch (e: Throwable) {
            e.printStackTrace()
        }
    }


    override fun onVideoSizeChange(
        width: Int,
        height: Int,
        unappliedRotationDegrees: Int,
        pixelWidthHeightRatio: Float,
        playerModel: IYzsPlayer.Model?
    ) {
        super.onVideoSizeChange(
            width,
            height,
            unappliedRotationDegrees,
            pixelWidthHeightRatio,
            playerModel
        )
        requestedOrientation =
            if (width >= height) {
                ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
            } else {
                ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
            }
    }

    override fun setRequestedOrientation(requestedOrientation: Int) {
        try {
            super.setRequestedOrientation(requestedOrientation)
        } catch (e: Throwable) {
            e.printStackTrace()
        }
    }
}